/*******************************************************************************
 * 文件名: HttpCorsFilter.java
 * 描    述: 远程控制设置过滤器
 * 创建人: Dean Huang(hudi-112@163.com)
 * 日　期: 2016-05-10
 * 描　述: 文件描述
 * 版　本: 1.0
 *******************************************************************************/

package com.z1.core.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class HttpCorsFilter implements Filter {

	private final String PARAM_ALLOW_ORGIN = "Access-Control-Allow-Origin";
	private final String PARAM_ALLOW_METHODS = "Access-Control-Allow-Methods";
	private final String PARAM_ALLOW_HEADERS = "Access-Control-Allow-Headers";
	
	private final String PARAM_ALLOW_ORGIN_DEFAULT = "*";
	private final String PARAM_ALLOW_METHODS_DEFAULT = "OPTIONS, POST, GET, PUT, DELETE";
	private final String PARAM_ALLOW_HEADERS_DEFAULT = "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, authorization, SOAPAction, token, user";
	
	private String allowOrgin = null;
	private String allowMethods = null;
	private String allowHeaders = null;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		//allowOrgin
		this.allowOrgin = config.getInitParameter(PARAM_ALLOW_ORGIN);
		if (null == this.allowOrgin || this.allowOrgin.trim().equals("")) {
			this.allowOrgin = PARAM_ALLOW_ORGIN_DEFAULT;
		}
		//allowMethods
		this.allowMethods = config.getInitParameter(PARAM_ALLOW_METHODS);
		if (null == this.allowMethods || this.allowMethods.trim().equals("")) {
			this.allowMethods = PARAM_ALLOW_METHODS_DEFAULT;
		}
		//allowHeaders
		this.allowHeaders = config.getInitParameter(PARAM_ALLOW_HEADERS);
		if (null == this.allowHeaders || this.allowHeaders.trim().equals("")) {
			this.allowHeaders = PARAM_ALLOW_HEADERS_DEFAULT;
		}
	}
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse)resp;  
		
		response.addHeader(PARAM_ALLOW_ORGIN, this.allowOrgin);
		response.addHeader(PARAM_ALLOW_METHODS, this.allowMethods);
		response.addHeader(PARAM_ALLOW_HEADERS, this.allowHeaders);
	    chain.doFilter(req, resp);
	}

	@Override
	public void destroy() {
	}

}
